package com.cskaoyan.demo2.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2024/6/27 11:13
 * @Version 1.0
 */
@RestController
public class FileUploadController {

    //将要提交一个file:xxxx文件数据，那么我们需要在方法形参编写一个变量叫做file，类型必须是MultipartFile
    @PostMapping("upload")
    public Object upload(MultipartFile file){
        String filename = file.getOriginalFilename();
        filename = UUID.randomUUID() + filename;
        String contentType = file.getContentType();
        long size = file.getSize();

        //此时，先不用着急将文件写入到应用根目录中，因为还没有介绍如何在controller里面获取ServletContext对象
        try {
            file.transferTo(new File("D:/image/" + filename));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return null;
    }
}
